<template>
  <div class="pdf-container">
    <template v-for="item in pageNum" :key="item">
      <canvas :id="`pdf-canvas-${item}`"></canvas>
    </template>
    <canvas id="pdf-canvas"></canvas>
  </div>
</template>

<script lang="ts" setup>
import * as PdfJs from "pdfjs-dist/legacy/build/pdf.js";
import { ref } from "vue";
import { PDFDocumentProxy } from "pdfjs-dist/legacy/build/pdf.js";
import { RenderParameters } from "pdfjs-dist/types/src/display/api";
import { useRouter } from "vue-router";
import globalConfig from "@/config/global-config";

const pageNum = ref(0);
const router = useRouter();

const location = globalConfig.pdf.location;
const url = ref();
url.value = location + router.currentRoute.value.query.file;

const loadFile = (url: string) => {
  // 设置 workerSrc 参数
  PdfJs.GlobalWorkerOptions.workerSrc = require("pdfjs-dist/build/pdf.worker.entry");

  const loadingTask = PdfJs.getDocument(url);
  (async () => {
    const pdf = (await loadingTask.promise) as PDFDocumentProxy;
    pageNum.value = pdf.numPages;
    //
    // Fetch the first page
    //
    for (let i = 1; i <= pdf.numPages; i++) {
      const page = await pdf.getPage(i);
      const scale = 1.5;
      const viewport = page.getViewport({ scale });
      // Support HiDPI-screens.
      const outputScale = window.devicePixelRatio || 1;

      //
      // Prepare canvas using PDF page dimensions
      //
      const canvas = document.getElementById(
        `pdf-canvas-${i}`
      ) as HTMLCanvasElement;
      console.log(typeof canvas);
      const context = canvas.getContext("2d");

      canvas.width = Math.floor(viewport.width * outputScale);
      canvas.height = Math.floor(viewport.height * outputScale);
      canvas.style.width = Math.floor(viewport.width) + "px";
      canvas.style.height = Math.floor(viewport.height) + "px";

      const transform =
        outputScale !== 1 ? [outputScale, 0, 0, outputScale, 0, 0] : null;

      //
      // Render PDF page into canvas context
      //
      const renderContext = {
        canvasContext: context,
        transform,
        viewport,
      } as RenderParameters;
      page.render(renderContext);
    }
  })();
};

loadFile(url.value);
</script>

<style scoped>
.pdf-container {
  width: 100%;
  height: 100%;
  position: absolute;
  text-align: center;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}
</style>
